<template>
  <div class="app-container">
    <el-row :gutter="20">
    <!--部门数据-->
    <el-col :span="4" :xs="24">
      <div class="head-container">
        <el-input
          v-model="locationName"
          placeholder="请输入位置信息"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 20px"
        />
      </div>
      <div class="head-container">
        <el-tree
          :data="deptOptions"
          :props="defaultProps"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          ref="tree"
          node-key="id"
          default-expand-all
          highlight-current
          @node-click="handleNodeClick"
        />
      </div>
    </el-col>
      <el-col :span="20" :xs="24">

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备编号" prop="equipmentNumber">
        <el-input
          v-model="queryParams.equipmentNumber"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-row  :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:device:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:device:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:device:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:device:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="水电设备ID" align="center" prop="id" />
      <el-table-column label="设备名称" align="center" prop="name" />
      <el-table-column label="设备状态 0有效 1无效" align="center" prop="status" >
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status == 0">正常</el-tag>
          <el-tag type="danger" v-if="scope.row.status == 1">无效</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="设备位置" align="center" prop="tierNaem" />
      <el-table-column label="设备类型" align="center" prop="deviceType">
        <template slot-scope="scope">
          <el-tag type="text" v-if="scope.row.deviceType == 1">电表</el-tag>
          <el-tag type="text" v-if="scope.row.deviceType == 2">水表</el-tag>
          <el-tag type="text" v-if="scope.row.deviceType == 3">消费机</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="设备编号" align="center" prop="equipmentNumber" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:device:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:device:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="operation('1',scope.row)"
            v-hasPermi="['system:device:remove']"
          >拉闸</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="operation('2',scope.row)"
            v-hasPermi="['system:device:remove']"
          >合闸</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="table()"
            v-hasPermi="['system:device:remove']"
          >抄表</el-button>
        </template>

      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
      </el-col>
    </el-row>
    <!-- 添加或修改水电设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="空间位置" prop="baseSpaceLocationId">
<!--          <el-input v-model="form.baseSpaceLocationId" placeholder="请输入空间id" />-->
          <treeselect v-model="form.baseSpaceLocationId"  :options="deptOptions" :normalizer="normalizer" placeholder="请选择上级id" />
        </el-form-item>
        <el-form-item label="所属网关" prop="iotGatewayId">
          <el-select v-model="form.iotGatewayId" placeholder="请选择网关">
            <el-option v-for="gateway in gatewayList" :key="gateway.id" :label="gateway.name" :value="gateway.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="form.deviceType" placeholder="1电表 2水表 3消费机">
            <el-option label="电表" value="1"></el-option>
            <el-option label="水表" value="2"></el-option>
            <el-option label="消费机" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备编号" prop="equipmentNumber">
          <el-input v-model="form.equipmentNumber" placeholder="请输入设备编号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { meterReading, listDevice, getDevice, delDevice, addDevice, updateDevice, electricity } from "@/api/yc-device/device";
import { listGateway } from "@/api/yc-gateway/gateway";
import { listLocation } from "@/api/yc-location/location";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Device",
  components: {
    Treeselect
  },
  data() {
    return {
      // 位置名称
      locationName: '',
      // 部门树选项
      deptOptions: [],
      defaultProps: {
        children: "children",
        label: "locationName"
      },
      // 所属网关
      gatewayList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 水电设备表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        equipmentNumber: null,
        tierNaemId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        baseSpaceLocationId: [
          { required: true, message: "空间位置不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        deviceType: [
          { required: true, message: "1电表  2水表 3消费机不能为空", trigger: "blur" }
        ],
        equipmentNumber: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getLocation();
    this.getGateway();
  },
  watch: {
    // 根据名称筛选部门树
    locationName(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    /** 查询设备网关列表 */
    getGateway() {
      this.loading = true;
      listGateway(null).then(response => {
        this.gatewayList = response.rows;
      });
    },
    /** 转换空间位置数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.locationName,
        children: node.children
      };
    },
    // 树形展示
    getLocation() {
      listLocation().then(response => {
        this.deptOptions = [];
        const data = { id: 0, locationName: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "id", "pid");
        this.deptOptions.push(data);
      });
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.tierNaemId = data.id;
      this.handleQuery();
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 查询水电设备列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        status: null,
        baseSpaceLocationId: null,
        iotGatewayId: null,
        deviceType: null,
        isDelete: null,
        createDate: null,
        modifyDate: null,
        equipmentNumber: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加水电设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDevice(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改水电设备";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除水电设备编号为"' + ids + '"的数据项？').then(function() {
        return delDevice(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    },
    operation(operationType,obj){
      electricity(operationType,obj.id).then(ret => {
        alert("看! 灯泡亮了！！！！！！！！");
      })
    },
    table(){
      meterReading().then(ret => {

      })
    }
  }
};
</script>
